
package com.yimixian.app.goods;

import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.PlusMinusIconMessage;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.cart.CartDetailActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.cart.CouDanFragment;
import com.yimixian.app.cart.GoodsItemPresenter;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.fragment.DialogGoodDetailFragment;
import com.yimixian.app.model.CartUpdate;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.rest.api.CartUpdateAPI;
import com.yimixian.app.ui.AnimationFrameLayout;
import com.yimixian.app.ui.DetailCartView;
import com.yimixian.app.ui.ParabolaView;
import com.yimixian.app.ui.PlusMinusIcon;
import com.yimixian.app.user.UserRegistrationActivity;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.PaoWuXianAnimTool;
import com.yimixian.app.util.PaoWuXianAnimator;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.UiUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import org.json.JSONObject;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.greenrobot.event.EventBus;

/**
 * A simple {@link Fragment} subclass.
 */
public class GoodDetailCartFragment extends DialogGoodDetailFragment implements View.OnClickListener,GoodsItemPresenter.OnPlusButtonClickListener {
    private AnimationFrameLayout mCart;
    private FrameLayout mPlucMinusIconContainer;
    private LocalBroadcastManager mBroadcastManager;
    private Handler mHandler = new Handler();
    private String mGoodId;

    @InjectView(R.id.bottom_cart_view)
    DetailCartView mBottomCartView;
    @InjectView(R.id.main_frame)
    RelativeLayout mMainFrame;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_good_detail_cart, container, false);
        ButterKnife.inject(this, view);
        if(!CartManager.getInstance().isUserLogin())CartManager.getInstance().setCartQuantityTextView(mBottomCartView.getTotalSimpleDescription());
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().registerSticky(this);
        }
        regQuantityChangeBroadcast();
        initPlusMinusIcon();
        CartManager.getInstance().sendQuantityChangeBroadCast();
        return view;
    }

    /**
     * 初始化 + / - 号
     */
    public void initPlusMinusIcon() {
        String goodId = getArguments().getString(GoodDetailActivity.INTENT_EXTRA_GOOD_ID);
        if(!TextUtils.isEmpty(goodId)) {
            mGoodId = goodId.trim();
        }
        GoodsItem item = null;
        if (!TextUtils.isEmpty(mGoodId)) {
            int goodid = 0;
            try {
                goodid = Integer.parseInt(mGoodId);
            } catch (NumberFormatException e) {

            }
            item = CartManager.getInstance().mIdToGoodsItem.get(goodid);
        }
        if (item == null) {
            return;
        }
        mCart = mBottomCartView.getCartViewIcon();
        if(mCart != null) {
            mCart.setOnClickListener(this);
        }
        if(mBottomCartView != null) {
            mPlucMinusIconContainer = mBottomCartView.getPlusMinusContainer();
            mPlusMinusIcon = new PlusMinusIcon(SystemFramework.getInstance().getGlobalContext(), item,
                Constants.STATE_DETAILFRAGMENT_BUTTON_BROADCAST);
            mPlusMinusIcon.setOnPlusButtonClickListener(this);
            mPlucMinusIconContainer.removeAllViews();
            mPlucMinusIconContainer.addView(mPlusMinusIcon);
            mPlusMinusIcon.setLl_go_shangcheng((LinearLayout) mBottomCartView.findViewById(R.id.ll_go_shangcheng));
//            try {
//                GoodDetailTopFragment fragment = (GoodDetailTopFragment) getFragmentManager()
//                        .findFragmentByTag("com.yimixian.app.goods.GoodDetailTopFragment");
//                if(fragment != null){
//                    if(fragment.getmPlusMinusIcon() == null)
//                        fragment.setmPlusMinusIcon(mPlusMinusIcon);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(mPlusMinusIcon != null) {
            mPlusMinusIcon.setEnabled(true);
        }
        mPlusMinusIcon = null;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mReceiver != null && mBroadcastManager != null) {
            mBroadcastManager.unregisterReceiver(mReceiver);
        }
    }

    @Override
    public void onResume() {
        if(mPlusMinusIcon != null) {
            mPlusMinusIcon.updatePlusMinusIconCount();
        }
        super.onResume();
    }

    public void regQuantityChangeBroadcast() {
        mBroadcastManager = LocalBroadcastManager.getInstance(SystemFramework
            .getInstance().getGlobalContext());
        IntentFilter filterAddressChange = new IntentFilter();
        filterAddressChange.addAction(Constants.QUANTITY_CHANGE_BROADCAST);
        mBroadcastManager.registerReceiver(mReceiver,
            filterAddressChange);
    }

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.QUANTITY_CHANGE_BROADCAST.equals(intent.getAction())) {
                int quantity = intent.getExtras().getInt(Constants.QUANTITY_CHANGE, 0);
                if (mBottomCartView != null && !mBottomCartView.isBadgeNumberIsNull()) {
                    mBottomCartView.setBadgeIcon(quantity);
                }
            }
        }
    };

    @Override
    public void initRequestAPI(String requestKeys) {
        if(requestKeys != null && CartUpdateAPI.CART_UPDATE_API.equals(requestKeys) && mCartUpdateAPI == null) {
            mCartUpdateAPI = new CartUpdateAPI(this);
        }
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        if(mCartUpdateAPI != null) {
            if (url.contains(mCartUpdateAPI.CART_UPDATE)) {
                CartUpdate cartUpdate = mCartUpdateAPI.parseJson(responseJson);
                CartManager.getInstance().updateCartGoods(cartUpdate, mPlusMinusIcon);
                if(mPlusMinusIcon != null) {
                    mPlusMinusIcon.setButtonCanClick(true);
                }
            }
        }
        hidePopupWindow();
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        if(mPlusMinusIcon != null) {
            mPlusMinusIcon.setButtonCanClick(true);
        }
        hidePopupWindow();
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        if(CartUpdateAPI.CART_UPDATE_API.equals(key)) {
            initRequestAPI(key);
        }
    }

    //    取消dialog框
    public void onEventMainThread(String message) {
        if(message != null) {
            if(Constants.EVENT_BUS_DISSMISS_DIALOG.equals(message)) {
                hidePopupWindow();
                if(mPlusMinusIcon != null) {
                    mPlusMinusIcon.setButtonCanClick(true);
                }
                EventBus.getDefault().removeStickyEvent(message);
            }
        }
    }

    // 发起商品 + / - 的请求
    public void onEventMainThread(PlusMinusIconMessage message) {
        if (message != null) {
            if(Constants.STATE_DETAILFRAGMENT_BUTTON_BROADCAST.equals(message.message) || (Constants.STATE_DETAILFRAGMENT_BUTTON_BROADCAST + "/IsFisrt").equals(message.message)) {
                mPlusMinusIcon = message.icon;
                dealPlusMinusProtocol();
                EventBus.getDefault().removeStickyEvent(message);
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cart:
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                        UMengConstants.NEW_GOODDETAIL_CARTBTN);
                String isFromCouDanPage = getActivity().getIntent().getStringExtra("isFromCouDanPage");
                if (isLogin()) {
                    if("1".equalsIgnoreCase(isFromCouDanPage)){
                        getActivity().setResult(CouDanFragment.FROM_COU_DAN);
                        getActivity().finish();
                    }else{
                        DateUtil.setCityUMeng(null, UMengConstants.NEW_BOTTOM_CARTBTN);
                        startActivity(CartDetailActivity.buildIntent(getActivity()));
                    }
                } else {
                    Intent intent = new Intent(getActivity(), UserRegistrationActivity.class);
                    startActivityForResult(intent, Constants.USER_REGISTRATION_REQUEST_CODE);
                }
                break;
        }
    }

    public boolean isLogin() {
        if (DataManager.getInstance().get(CacheKeys.TOKEN) == null) {
            return false;
        }
        return true;
    }

    @Override
    public void onPlusButtonClick(View plusView, Point point, Bitmap animBack) {

        PaoWuXianAnimTool.startAnim(getActivity(), plusView, mCart, animBack, 100, PaoWuXianAnimTool.DEFAULT_DURATION);

        if(true)
            return;

        ParabolaView parabolaView = new ParabolaView(getActivity(), animBack);
        if (mMainFrame != null) {
            mMainFrame.addView(parabolaView);
        }
        if(mCart != null) {
            parabolaView.startAnimation(mHandler, mCart.getCartLocationPoint(),
                    point);
        }
    }

    @Override
    public void onDetach() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDetach();
    }


}
